#!/bin/bash

set -e
# Define Docker data directory variable
export DOCKER_DATA_ROOT="/data/docker"
VERSION=19.03.9

# Function to check the success of each command
check_command() {
  if [ $? -ne 0 ]; then
    echo "Error: $1 failed."
    exit 1
  fi
}

# Function to add a repository if it does not exist
add_repo_if_not_exists() {
  local repo_name=$1
  local repo_url=$2
  # shellcheck disable=SC2155
  if ! ls /etc/yum.repos.d | grep -q "$repo_name"; then
    wget -O /etc/yum.repos.d/"$repo_name" "$repo_url" > /dev/null
    check_command "Adding repository $repo_url"
    echo "Repository $repo_name added successfully."
  else
    echo "Repository $repo_name already exists."
  fi
}

# Add Centos-7 repository
echo "Step1: Centos-7 仓库添加"
add_repo_if_not_exists "Centos-7.repo" "http://mirrors.aliyun.com/repo/Centos-7.repo"
echo " "

# Add EPEL repository
echo "Step2: epel-7 仓库添加"
add_repo_if_not_exists "epel-7.repo" "http://mirrors.aliyun.com/repo/epel-7.repo"
echo " "

# Add Docker CE repository
echo "Step3: Docker 仓库添加"
yum install -y --setopt=tsflags=nodocs yum-utils device-mapper-persistent-data lvm2
check_command "Installing dependencies for Docker CE"
yum-config-manager --add-repo "http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo" > /dev/null
echo " "

# Install Docker CE
echo "Step4: Docker-ce 开始下载安装"
yum -y --setopt=tsflags=nodocs install docker-ce-$VERSION docker-compose docker-ce-cli-$VERSION
check_command "Installing Docker CE"
echo " "

mkdir -p $DOCKER_DATA_ROOT
mkdir -p /etc/docker

# Configure Docker registry mirror
echo "Step5: 镜像加速配置"
cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": [
    "https://docker.m.daocloud.io",
    "https://huecker.io",
    "https://dockerhub.timeweb.cloud",
    "https://noohub.ru"
  ],
  "data-root": "$DOCKER_DATA_ROOT"
}
EOF
check_command "Configuring Docker registry mirrors"
echo " "

# Enable and start Docker service
echo "Step6: Docker 设置开机自启动"
systemctl enable docker
check_command "Enabling Docker to start at boot"
systemctl start docker
check_command "Starting Docker service"
echo " "

echo "======================================"
echo "Docker 已安装成功"
